package com.analysis.controller;

import com.analysis.dto.ApiResponse;
import com.analysis.entity.Project;
import com.analysis.entity.ProjectBrand;
import com.analysis.entity.User;
import com.analysis.enums.RequireLogin;
import com.analysis.service.ProjectBrandService;
import com.analysis.service.ProjectService;
import com.analysis.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目品牌信息管理
 */
@RestController
@RequestMapping("/api/project/brands")
@CrossOrigin(origins = "*")
public class ProjectBrandController {

    @Autowired
    private ProjectBrandService projectBrandService;

    @Autowired
    private ProjectService projectService;


    /**
     * 保存项目品牌（如果存在相同projectId则修改，否则新增）
     */
    @PostMapping("/save")
    @RequireLogin
    public ApiResponse<ProjectBrand> save(@RequestBody ProjectBrand projectBrand, HttpServletRequest request) {
        try {
            initProjectId(projectBrand, request);

            // 检查是否已存在相同projectId的品牌
            ProjectBrand existingBrand = projectBrandService.getSelectedByProjectId(projectBrand.getProjectId());

            if (existingBrand != null) {
                // 存在则更新
                projectBrand.setId(existingBrand.getId());
                int result = projectBrandService.update(projectBrand);
                return result > 0 ? ApiResponse.success(projectBrandService.getById(existingBrand.getId())) : ApiResponse.error("更新失败");
            } else {
                // 不存在则新增
                int result = projectBrandService.create(projectBrand);
                return result > 0 ? ApiResponse.success(projectBrand) : ApiResponse.error("创建失败");
            }
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("保存品牌信息时发生错误: " + e.getMessage());
        }
    }

    /**
     * 查询当前选中的品牌
     */
    @GetMapping("/selected")
    @RequireLogin
    public ApiResponse<ProjectBrand> getSelected(HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法查询品牌信息");

            // 获取当前选中的项目（按公司）
            Project selectedProject = projectService.getSelectedByCompanyId(currentUser.getCompanyId());
            if (selectedProject == null) {
                return ApiResponse.error("请先选择一个项目");
            }

            ProjectBrand selectedBrand = projectBrandService.getSelectedByProjectId(selectedProject.getId());
            return ApiResponse.success(selectedBrand);
        } catch (Exception e) {
            return ApiResponse.error("查询当前选中品牌时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/delete")
    @RequireLogin
    public ApiResponse<String> delete(HttpServletRequest request, Long id) {
        try {
            Long projectId = getProjectId(request);

            // 检查项目是否存在且属于当前用户
            ProjectBrand existing = projectBrandService.getById(id);
            if (existing == null || !existing.getProjectId().equals(projectId)) {
                return ApiResponse.error("无权限操作");
            }

            int result = projectBrandService.delete(id);
            return result > 0 ? ApiResponse.success("删除成功") : ApiResponse.error("删除失败或不存在");
        } catch (Exception e) {
            return ApiResponse.error("删除品牌信息时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/add")
    @RequireLogin
    public ApiResponse<ProjectBrand> create(@RequestBody ProjectBrand projectBrand, HttpServletRequest request) {
        try {
            initProjectId(projectBrand, request);

            int result = projectBrandService.create(projectBrand);
            return result > 0 ? ApiResponse.success(projectBrand) : ApiResponse.error("创建失败");
        } catch (Exception e) {
            return ApiResponse.error("创建品牌信息时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    @RequireLogin
    public ApiResponse<ProjectBrand> update(@RequestBody ProjectBrand projectBrand, HttpServletRequest request) {
        try {
            // 验证品牌信息是否存在且属于当前用户的项目
            ProjectBrand existingBrand = projectBrandService.getById(projectBrand.getId());
            if (existingBrand == null) {
                return ApiResponse.error("品牌信息不存在");
            }

            Long projectId = getProjectId(request);
            Project project = projectService.getById(projectId);
            if (project == null || !project.getId().equals(existingBrand.getProjectId())) {
                return ApiResponse.error("无权限操作此品牌信息");
            }

            // 检查filter_name是否重复（排除当前记录）
            if (projectBrand.getFilterName() != null && !projectBrand.getFilterName().trim().isEmpty()) {
                ProjectBrand duplicateBrand = projectBrandService.getByProjectIdAndFilterName(existingBrand.getProjectId(), projectBrand.getFilterName());
                if (duplicateBrand != null && !duplicateBrand.getId().equals(projectBrand.getId())) {
                    return ApiResponse.error("品牌名称已存在，请使用其他名称");
                }
            }

            int result = projectBrandService.update(projectBrand);
            return result > 0 ? ApiResponse.success(projectBrandService.getById(projectBrand.getId())) : ApiResponse.error("更新失败或不存在");
        } catch (Exception e) {
            return ApiResponse.error("更新品牌信息时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/get")
    @RequireLogin
    public ApiResponse<ProjectBrand> getById(Long id, HttpServletRequest request) {
        try {
            Long projectId = getProjectId(request);
            ProjectBrand data = projectBrandService.getById(id);
            if (data == null || !data.getProjectId().equals(projectId)) {
                return ApiResponse.error("品牌信息不存在");
            }
            return ApiResponse.success(data);
        } catch (Exception e) {
            return ApiResponse.error("查询品牌信息详情时发生错误: " + e.getMessage());
        }
    }

    /**
     * 查询项目品牌列表
     */
    @GetMapping("/list")
    @RequireLogin
    public ApiResponse<List<ProjectBrand>> list(HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法查询品牌信息");

            // 获取当前选中的项目（按公司）
            Project selectedProject = projectService.getSelectedByCompanyId(currentUser.getCompanyId());
            if (selectedProject == null) {
                return ApiResponse.error("请先选择一个项目");
            }

            List<ProjectBrand> data = projectBrandService.listByProjectIds(List.of(selectedProject.getId()));
            return ApiResponse.success(data);
        } catch (Exception e) {
            return ApiResponse.error("查询品牌信息列表时发生错误: " + e.getMessage());
        }
    }

    /**
     * 分页查询项目品牌
     */
    @GetMapping("/page")
    @RequireLogin
    public ApiResponse<Map<String, Object>> page(@RequestParam(defaultValue = "1") int pageNum,
                                                 @RequestParam(defaultValue = "10") int pageSize,
                                                 HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法查询品牌信息");

            // 获取当前选中的项目（按公司）
            Project selectedProject = projectService.getSelectedByCompanyId(currentUser.getCompanyId());
            if (selectedProject == null) {
                return ApiResponse.error("请先选择一个项目");
            }

            List<ProjectBrand> data = projectBrandService.page(selectedProject.getId(), pageNum, pageSize);
            int total = projectBrandService.count(selectedProject.getId());

            Map<String, Object> result = new HashMap<>();
            result.put("list", data);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("分页查询品牌信息时发生错误: " + e.getMessage());
        }
    }


    /**
     * 选择品牌
     */
    @PostMapping("/select")
    @RequireLogin
    public ApiResponse<String> selectBrand(@RequestParam Long brandId, HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法选择品牌");

            // 获取当前选中的项目
            Project selectedProject = projectService.getSelectedByCompanyId(currentUser.getCompanyId());
            if (selectedProject == null) {
                return ApiResponse.error("请先选择一个项目");
            }

            // 验证品牌是否属于当前项目
            ProjectBrand brand = projectBrandService.getById(brandId);
            if (brand == null || !brand.getProjectId().equals(selectedProject.getId())) {
                return ApiResponse.error("品牌不存在或无权限操作");
            }

            int result = projectBrandService.selectBrand(selectedProject.getId(), brandId);
            return result > 0 ? ApiResponse.success("品牌选择成功") : ApiResponse.error("品牌选择失败");
        } catch (Exception e) {
            return ApiResponse.error("选择品牌时发生错误: " + e.getMessage());
        }
    }

    /**
     * 取消所有品牌选中状态
     */
    @PostMapping("/unselect")
    @RequireLogin
    public ApiResponse<String> unselectAll(HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法取消选择");

            // 获取当前选中的项目
            Project selectedProject = projectService.getSelectedByCompanyId(currentUser.getCompanyId());
            if (selectedProject == null) {
                return ApiResponse.error("请先选择一个项目");
            }

            int result = projectBrandService.unselectAllByProjectId(selectedProject.getId());
            return ApiResponse.success("取消选择成功");
        } catch (Exception e) {
            return ApiResponse.error("取消选择时发生错误: " + e.getMessage());
        }
    }


    public void initProjectId(ProjectBrand projectBrand, HttpServletRequest request) {
        Long companyId = UserUtils.getCurrentUser(request).getCompanyId();
        Project project = projectService.getSelectedByCompanyId(companyId);
        if (project == null) {
            throw new IllegalArgumentException("项目不存在或无权限操作");
        }
        projectBrand.setProjectId(project.getId());
        projectBrand.setCompanyId(companyId);
    }

    public Long getProjectId(HttpServletRequest request) {
        Long companyId = UserUtils.getCurrentUser(request).getCompanyId();
        Project project = projectService.getSelectedByCompanyId(companyId);
        if (project == null) {
            throw new IllegalArgumentException("项目不存在或无权限操作");
        }
        return project.getId();
    }
}
